package com.redis.controller;

import org.redisson.api.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
public class RateLimiterController {
    @Resource
    private RedissonClient redissonClient;

    static {

    }



    @RequestMapping("/rateLimiter.json")
    public void  rateLimiter(){
        RRateLimiter rateLimiter = redissonClient.getRateLimiter("myRateLimiter");

        // 获取4个令牌
        boolean b1 = rateLimiter.tryAcquire(1);

        System.out.println(b1);
//        // 尝试获取4个令牌，尝试等待时间为2秒钟
//        boolean b2 = rateLimiter.tryAcquire(1, 2, TimeUnit.SECONDS);
//
//        System.out.println(b2);
//        RFuture<Boolean> booleanRFuture = rateLimiter.tryAcquireAsync(2, 2, TimeUnit.SECONDS);
//
//        // 尝试获取1个令牌，等待时间不限
//        rateLimiter.acquire();
//
//
//
//
//        // 尝试获取1个令牌，等待时间不限
//        RFuture<Void> future = rateLimiter.acquireAsync();
    }
    @RequestMapping("/rateLimiter2.json")
    public void  rateLimiter2(){
        RRateLimiter rateLimiter1 = redissonClient.getRateLimiter("myRateLimsssssssssiter");
        boolean b = rateLimiter1.trySetRate(RateType.PER_CLIENT, 5, 1, RateIntervalUnit.SECONDS);


        RRateLimiter rateLimiter = redissonClient.getRateLimiter("myRateLimsssssssssiter");
        // 获取4个令牌
        boolean b1 = rateLimiter.tryAcquire(5);
        System.out.println(b1);
        boolean b3 = rateLimiter.tryAcquire(1);
        System.out.println(b3);

        // 尝试获取4个令牌，尝试等待时间为2秒钟
        boolean b2 = rateLimiter.tryAcquire(1, 2, TimeUnit.SECONDS);
        System.out.println(b2);


//        RFuture<Boolean> booleanRFuture = rateLimiter.tryAcquireAsync(2, 2, TimeUnit.SECONDS);
//        System.out.println(booleanRFuture);
//
//
//        // 尝试获取1个令牌，等待时间不限
//        rateLimiter.acquire();
//
//        // 尝试获取1个令牌，等待时间不限
//        RFuture<Void> future = rateLimiter.acquireAsync();
    }
}
